package com.johnny.springai.modelstructuredagent.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

import com.johnny.springai.modelstructuredagent.config.AiJob;

@RestController
public class MultiModelsController {
    @Autowired
    private ChatClient planningChatClient;

    @Autowired
    private ChatClient botChatClient;

    @RequestMapping(value = "/stream", produces = "text/stream;charset=UTF-8")
    Flux<String> stream(@RequestParam String message) {

        //创建一个哟关于多条消息的 Sink  (流式相应)
        Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
        //推从消息
        sink.tryEmitNext("正在计划任务....<br>");

        new Thread(() -> {

            AiJob.Job job = planningChatClient.prompt()
                    .user(message)
                    .call()
                    .entity(AiJob.Job.class);

            switch (job.jobType()) {
                case CANCEL -> {
                    System.out.println(job);// todo.. 执行业务
                    if (job.keyInfos().size() == 0) {
                        sink.tryEmitNext("请输入姓名和订单号");
                    } else {
                        //todo 执行退票业务逻辑 ticketService.cancel();
                        sink.tryEmitNext("退票成功!");
                    }
                }
                case QUERY -> {
                    System.out.println(job);// todo.. 执行业务
                    if (job.keyInfos().size() == 0) {
                        sink.tryEmitNext("请输入姓名和订单号");
                    } else {
                        //todo 执行查票业务逻辑 ticketService.query();
                        sink.tryEmitNext("查询预定信息:xxxx");
                    }
                }
                case OTHER -> {
                    Flux<String> content = botChatClient.prompt().user(message).stream().content();
                    content.doOnNext( sink::tryEmitNext)//推送每条AI流内容
                            .doOnComplete(()-> sink.tryEmitComplete())
                            .subscribe();
                }
                default -> {
                    System.out.println(job);
                    sink.tryEmitNext("解析失败");
                }
            }
            }).start();
            return sink.asFlux();
        }
    }

